package com.zgg.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域处理
 *
 * @author chencq
 * @email chenchaoqun@incar100.com
 */
public class CorsFilter implements Filter {
    private static final Logger LOG = LoggerFactory.getLogger(CorsFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse hres = (HttpServletResponse) response;
        // 指定允许其他域名访问
        hres.setHeader("Access-Control-Allow-Origin", "*");
        // 响应类型
        hres.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS");
        hres.setHeader("Access-Control-Max-Age", "3600");
        hres.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type,  channel, Accept");
        // 响应头设置
        hres.setHeader("Access-Control-Expose-Headers", "*");


        HttpServletRequest req = (HttpServletRequest) request;

        LOG.info("=============>>>>>  request method     :      {}", req.getMethod());
        //浏览器ajax发起
        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            hres.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        chain.doFilter(request, hres);
    }

    @Override
    public void destroy() {
    }

}
